package cn.wolfcode.mq.listener;


import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.domain.SeckillProduct;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@RocketMQMessageListener(
        consumerGroup = "OrderPayTimeoutGroup",
        topic = MQConstant.ORDER_PAY_TIMEOUT_TOPIC
)
public class OrderPayTimeoutListener implements RocketMQListener<OrderMQResult> {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private IOrderInfoService orderInfoService;

    @Override
    public void onMessage(OrderMQResult result) {
        System.err.println("延时消费中。。。");
        //1 判断订单状态是否是未支付
        OrderInfo orderInfo = orderInfoService.getOrderById(result.getOrderNo());
        //已支付
        if (StringUtils.isEmpty(orderInfo) ||orderInfo.getStatus() != OrderInfo.STATUS_ARREARAGE) {
            return;
        }
        //超时未支付
        //1 修改订单状态为超时取消
        int m = orderInfoService.changeTimeOut(result.getOrderNo());
        if (m < 1) {
            throw new BusinessException(SeckillCodeMsg.SECKILL_ERROR);
        }
        //2 表的真实库存+1操作
        m = seckillProductService.inscrStore(result.getSeckillId());
        if (m < 1) {
            throw new BusinessException(SeckillCodeMsg.SECKILL_ERROR);
        }
        //1 同步预库存
        //2 广播消息,本地表示设置为true

        //1 同步预库存
        SeckillProduct seckillProduct = seckillProductService.queryFomDB(result.getSeckillId());
        String bigKey = SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(result.getTime().toString());
        redisTemplate.opsForHash().put(bigKey, String.valueOf(result.getSeckillId()), seckillProduct.getStockCount().toString());

        //2 广播消息,本地表示设置为true
        rocketMQTemplate.sendOneWay(MQConstant.CANCEL_SECKILL_OVER_SIGE_TOPIC, result.getSeckillId().toString());

    }
}
